package cn.com.bluemoon.daps.common.datascope.encry;

import cn.com.bluemoon.datasecurity.app.sdk.RemoteCryptoModuleService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 *  加密包装对象
 * @author Lilike on 2022/2/18
 */
@Component
public class AesWapper {

    @Value("${spring.profiles.active}")
    private String profilesActive;

    @Autowired
    @Lazy
    private RemoteCryptoModuleService cryptoKeyService;

    /**
     * aes秘钥 长度32
     */
    private static String SYS_AUTH_SECRECT = "331d889686f844ca95ca5af939de5a87";
    private static AES aes = SecureUtil.aes(SYS_AUTH_SECRECT.getBytes());

    public String encryptBase64(String str) {
        checkSecrectKey();
        return aes.encryptBase64(str);
    }

    public String decryptStr(String str) {
        checkSecrectKey();
        return aes.decryptStr(str);
    }

    private void checkSecrectKey() {
        String newEncryKey = cryptoKeyService.getEncryPsw().getContent();
        if (!SYS_AUTH_SECRECT.equals(newEncryKey)) {
            SYS_AUTH_SECRECT = newEncryKey;
            aes = SecureUtil.aes(SYS_AUTH_SECRECT.getBytes());
        }
    }

    /**
     * 非生产环境，支持开启后门参看解密明文
     * @return
     */
    public boolean isEnableDecrypt() {
        if(!profilesActive.equalsIgnoreCase("prod")) {
            // 获取request
            ServletRequestAttributes servletRequestAttributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            if(request != null) {
                String testPsw = request.getParameter("testEncryPsw");
                if (StrUtil.equals(testPsw, SYS_AUTH_SECRECT)) {
                    return true;
                }
            }
        }
        return false;
    }

}
